package com.ruoyi.demo.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * 灵活的日期反序列化器
 * 支持多种日期格式，如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss 等
 *
 * @author metaee
 */
public class FlexibleDateDeserializer extends JsonDeserializer<Date> {

    private static final String[] PATTERNS = {
            "yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss"
    };

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        String dateStr = jsonParser.getText();
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }

        try {
            return DateUtils.parseDate(dateStr, PATTERNS);
        } catch (ParseException e) {
            throw new IOException("无法解析日期: " + dateStr, e);
        }
    }
}
